package com.fzt.system.service.security;

import com.fzt.framework.user.UserDetail;
import com.fzt.system.convert.SysUserConvert;
import com.fzt.system.domain.entity.SysUserEntity;
import com.fzt.system.mapper.SysUserMapper;
import com.fzt.system.service.SysMenuService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 实现spring security中的UserDetailsService接口
 * </p>
 *
 * @author 非洲铜
 * @since 2022-12-07
 */
@Service
@AllArgsConstructor
public class UserDetailService implements UserDetailsService {

    private final SysUserMapper  sysUserMapper;
    private final SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity sysUser = sysUserMapper.loadUserByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return getUserDetails(sysUser);
    }


    private UserDetails getUserDetails(SysUserEntity sysUserEntity) {
        UserDetail userDetail = SysUserConvert.INSTANCE.convertUserDetail(sysUserEntity);

        // 用户权限列表
        Set<String>                 authoritySet = sysMenuService.getUserAuthority(userDetail);
        Set<SimpleGrantedAuthority> authorities  = authoritySet.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());

        userDetail.setAuthorities(authorities);

        return userDetail;
    }
}
